/**
 * 用户模型
 * PC微信聊天应用 - 用户数据操作
 */

const { db } = require('../config/database');

class User {
  /**
   * 根据微信号和密码查找用户
   * @param {string} wxid 微信号
   * @param {string} password 密码
   * @returns {Promise<Object|null>} 用户信息
   */
  static async findByCredentials(wxid, password) {
    try {
      const sql = `
        SELECT id, wxid, nickname, icon, sex, summary, remark, area, letter, robot, status
        FROM users 
        WHERE wxid = ? AND password = ?
      `;
      const users = await db.query(sql, [wxid, password]);
      return users.length > 0 ? users[0] : null;
    } catch (error) {
      console.error('查找用户错误:', error);
      throw error;
    }
  }

  /**
   * 根据ID查找用户
   * @param {number} id 用户ID
   * @returns {Promise<Object|null>} 用户信息
   */
  static async findById(id) {
    try {
      const sql = `
        SELECT id, wxid, nickname, icon, sex, summary, remark, area, letter, robot, status, last_login
        FROM users 
        WHERE id = ?
      `;
      const users = await db.query(sql, [id]);
      return users.length > 0 ? users[0] : null;
    } catch (error) {
      console.error('根据ID查找用户错误:', error);
      throw error;
    }
  }

  /**
   * 更新用户在线状态
   * @param {number} userId 用户ID
   * @param {string} status 状态 (online/offline/busy)
   * @returns {Promise<boolean>} 更新结果
   */
  static async updateStatus(userId, status) {
    try {
      const sql = `
        UPDATE users 
        SET status = ?, last_login = CURRENT_TIMESTAMP 
        WHERE id = ?
      `;
      const result = await db.query(sql, [status, userId]);
      return result.affectedRows > 0;
    } catch (error) {
      console.error('更新用户状态错误:', error);
      throw error;
    }
  }

  /**
   * 获取用户好友列表
   * @param {number} userId 用户ID
   * @returns {Promise<Array>} 好友列表
   */
  static async getFriends(userId) {
    try {
      const sql = `
        SELECT 
          u.id, u.wxid, u.nickname, u.icon, u.sex, u.summary, 
          u.remark, u.area, u.letter, u.robot, u.status
        FROM users u
        INNER JOIN friendships f ON u.id = f.friend_id
        WHERE f.user_id = ? AND f.status = 'accepted'
        ORDER BY u.letter ASC, u.nickname ASC
      `;
      return await db.query(sql, [userId]);
    } catch (error) {
      console.error('获取好友列表错误:', error);
      throw error;
    }
  }

  /**
   * 搜索用户
   * @param {string} keyword 搜索关键词
   * @param {number} currentUserId 当前用户ID
   * @returns {Promise<Array>} 搜索结果
   */
  static async search(keyword, currentUserId) {
    try {
      const sql = `
        SELECT id, wxid, nickname, icon, sex, summary, area, robot
        FROM users 
        WHERE (wxid LIKE ? OR nickname LIKE ?) 
        AND id != ?
        LIMIT 20
      `;
      const searchTerm = `%${keyword}%`;
      return await db.query(sql, [searchTerm, searchTerm, currentUserId]);
    } catch (error) {
      console.error('搜索用户错误:', error);
      throw error;
    }
  }

  /**
   * 创建新用户
   * @param {Object} userData 用户数据
   * @returns {Promise<number>} 新用户ID
   */
  static async create(userData) {
    try {
      const sql = `
        INSERT INTO users (wxid, nickname, password, icon, sex, summary, area, letter)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      `;
      const { wxid, nickname, password, icon, sex, summary, area, letter } = userData;
      const result = await db.query(sql, [wxid, nickname, password, icon, sex, summary, area, letter]);
      return result.insertId;
    } catch (error) {
      console.error('创建用户错误:', error);
      throw error;
    }
  }

  /**
   * 更新用户信息
   * @param {number} userId 用户ID
   * @param {Object} updateData 更新数据
   * @returns {Promise<boolean>} 更新结果
   */
  static async update(userId, updateData) {
    try {
      const fields = [];
      const values = [];
      
      Object.keys(updateData).forEach(key => {
        if (updateData[key] !== undefined) {
          fields.push(`${key} = ?`);
          values.push(updateData[key]);
        }
      });
      
      if (fields.length === 0) return false;
      
      values.push(userId);
      const sql = `UPDATE users SET ${fields.join(', ')} WHERE id = ?`;
      const result = await db.query(sql, values);
      return result.affectedRows > 0;
    } catch (error) {
      console.error('更新用户信息错误:', error);
      throw error;
    }
  }

  /**
   * 检查用户是否存在
   * @param {string} wxid 微信号
   * @returns {Promise<boolean>} 是否存在
   */
  static async exists(wxid) {
    try {
      const sql = 'SELECT COUNT(*) as count FROM users WHERE wxid = ?';
      const result = await db.query(sql, [wxid]);
      return result[0].count > 0;
    } catch (error) {
      console.error('检查用户是否存在错误:', error);
      throw error;
    }
  }

  /**
   * 获取在线用户列表
   * @returns {Promise<Array>} 在线用户列表
   */
  static async getOnlineUsers() {
    try {
      const sql = `
        SELECT id, wxid, nickname, icon, status, last_login
        FROM users 
        WHERE status = 'online'
        ORDER BY last_login DESC
      `;
      return await db.query(sql);
    } catch (error) {
      console.error('获取在线用户错误:', error);
      throw error;
    }
  }

  /**
   * 批量获取用户信息
   * @param {Array} userIds 用户ID数组
   * @returns {Promise<Array>} 用户信息列表
   */
  static async findByIds(userIds) {
    try {
      if (!userIds || userIds.length === 0) return [];
      
      const placeholders = userIds.map(() => '?').join(',');
      const sql = `
        SELECT id, wxid, nickname, icon, sex, summary, remark, area, letter, robot, status
        FROM users 
        WHERE id IN (${placeholders})
      `;
      return await db.query(sql, userIds);
    } catch (error) {
      console.error('批量获取用户信息错误:', error);
      throw error;
    }
  }
}

module.exports = User;
